package com.huanzhidadi.single.produceconsumer;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 对比SynchronousQueueTest
 */
@Slf4j
public class CountdownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        AtomicReference<Object> atomicReference= new AtomicReference<>();
        CountDownLatch countDownLatch = new CountDownLatch(1);

        Runnable producer = () -> {
            log.info("生产者开始生产，请等待。。。");
            Object object = new Object();
            atomicReference.set(object);
            try {
                Thread.sleep(2000l);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("产品生产完成。");
            log.info("produced {}", object);
            countDownLatch.countDown();
        };

        Runnable consumer = () -> {
            try {
                log.info("消费者等待中。。。");
                countDownLatch.await();
                Object object = atomicReference.get();
                log.info("消费者得到产品");
                log.info("consumed {}", object);
            } catch (InterruptedException ex) {
                log.error(ex.getMessage(),ex);
            }
        };

        executor.submit(producer);
        executor.submit(consumer);

        executor.awaitTermination(5000, TimeUnit.MILLISECONDS);
        executor.shutdown();
    }
}
